package com.rong.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.rong.bean.Result;
import com.rong.bean.UserBean;
import com.rong.dao.impl.UserDao;

@Controller
@RequestMapping(value = "user")
public class UserController {
	public UserDao userDao;

	@Resource
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	@RequestMapping(value = "userRegister", produces = "text/plain;charset=utf-8", method = RequestMethod.POST)
	@ResponseBody
	public String userRegister(HttpServletRequest req) {
		String json = req.getParameter("params");
		System.out.println(json + "");
		
		Result result = new Result();
		try {
			JSONObject user = JSONObject.parseObject(json);
			UserBean userBean = new UserBean();
			userBean.setuName(user.getString("uName"));
			userBean.setuPwd(user.getString("uPwd"));
			boolean isOk = userDao.userRegister(userBean);
			if (isOk) {
				result.setCode(1);
				result.setMsg("注册成功！");
				return JSONObject.toJSONString(result);
			} else {
				result.setCode(-1);
				result.setMsg("用户名已存在！");
				return JSONObject.toJSONString(result);
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(-1);
			result.setMsg("请求参数错误！");
			return JSONObject.toJSONString(result);
		}
	}

	@RequestMapping(value = "userLogin", produces = "text/plain;charset=utf-8", method = RequestMethod.POST)
	@ResponseBody
	public String userLogin(HttpServletRequest req) {
		String json = req.getParameter("params");
		System.out.println(json + "");

		try {
			JSONObject user = JSONObject.parseObject(json);
			UserBean userBean = new UserBean();
			userBean.setuName(user.getString("uName"));
			userBean.setuPwd(user.getString("uPwd"));
			UserBean resultUser = userDao.userLogin(userBean);
			if (resultUser != null) {
				Result<UserBean> result = new Result<UserBean>();
				result.setCode(1);
				result.setMsg("登录成功！");
				result.setData(resultUser);
				return JSONObject.toJSONString(result);
			} else {
				Result result = new Result();
				result.setCode(-1);
				result.setMsg("用户名或密码有误！");
				return JSONObject.toJSONString(result);
			}
		} catch (Exception e) {
			e.printStackTrace();
			Result result = new Result();
			result.setCode(-1);
			result.setMsg("请求参数错误！");
			return JSONObject.toJSONString(result);
		}
	}
}
